package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlertRuleJob {

    @Autowired
    private AlertRuleService alertRuleService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Scheduled(cron = "0 * * * * ?")
    private void FilterAlertRule(){
        //1.查询所有规则
        List<AlertRuleVo> alertRuleVoList = alertRuleService.getAlertRuleVoAll(null,null,null);
        //判断是否为空 为空直接结束
        if (CollUtil.isEmpty(alertRuleVoList)){
            return;
        }
        //2.查询所有设备上报的数据
        List<Object> JsonStrList = redisTemplate.opsForHash().values(CacheConstants.DEVICE_LASTDATA_CACHE_KEY);
        //判断是否为空 为空直接结束
        if (CollUtil.isEmpty(JsonStrList)){
            return;
        }
        //3.数据格式标准化处理
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        JsonStrList.forEach(value ->{
            deviceDataVoList.addAll(JSONUtil.toList(value.toString(), DeviceDataVo.class));
        });
        //4.数据报警处理器
        deviceDataVoList.forEach(deviceDataVo -> alertRuleService.AlertRuleDeviceDateCheck(deviceDataVo));
    }
}
